﻿using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace EuphoricEngine3D
{
    public class IEContentManager : ContentManager
    {
        Dictionary<string, object> _loaded = new Dictionary<string, object>();
        List<IDisposable> _disposableAssets = new List<IDisposable>();

        public IEContentManager(IServiceProvider services)
            : base (services)
        {
        }

        public IEContentManager(IServiceProvider services, string rootDirectory)
            : base (services, rootDirectory)
        {
        }

        public override T Load<T>(string assetName)
        {
            if (_loaded.ContainsKey(assetName))
                return (T)_loaded[assetName];

            T read = base.ReadAsset<T>(assetName, RecordDisposableAsset);
            _loaded.Add(assetName, read);

            return read;
        }

        void RecordDisposableAsset(IDisposable disposable)
        {
            _disposableAssets.Add(disposable);
        }

        public T LoadFreshCopy<T>(string assetName)
        {
            return base.ReadAsset<T>(assetName, null);
        }

        public void UnloadAsset(string name)
        {
            if (_loaded.ContainsKey(name))
            {
                if (_loaded[name] is IDisposable && _disposableAssets.Contains((IDisposable)_loaded[name]))
                {
                    IDisposable disp = (IDisposable)_loaded[name];
                    _disposableAssets.Remove(disp);
                    disp.Dispose();
                }

                _loaded.Remove(name);
            }
        }

        public override void Unload()
        {
            foreach (IDisposable disposable in _disposableAssets)
                disposable.Dispose();

            _loaded.Clear();
            _disposableAssets.Clear();
        }
    }
}
